package com.hl.vcd.controller;

import com.hl.common.result.R;
import com.hl.common.result.ResponseEnum;
import com.hl.common.utils.JwtUtils;
import com.hl.vcd.service.CmsService;
import com.hl.vcd.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 朱炫达
 */
@RestController
@Slf4j
@RequestMapping("/api/cms")
public class CmsController {

    private CmsService cmsService;
    @Autowired
    public void setCmsService(CmsService cmsService){
        this.cmsService = cmsService;
    }

    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<String,String> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/send/{addressee}")
    public R sendEmail(@PathVariable String addressee){
//        //从redis获取验证码，防止重复发送
        String codeFromRedis = redisTemplate.opsForValue().get(addressee);
        if (!StringUtils.isEmpty(codeFromRedis)){
            return R.ok().message("验证码发送成功");
        }

        String code = RandomUtil.getSixBitRandom();
        R r = cmsService.sendEmail(addressee, code, 1);
        if(Objects.equals(r.getCode(), ResponseEnum.SUCCESS.getCode())){
            //放入redis
            redisTemplate.opsForValue().set(addressee,code,5, TimeUnit.MINUTES);
        }
        return r;
    }

    @GetMapping("/send_password_email")
    public R sendUpdatePasswordEmail(@RequestHeader Map<Object,Object> map){
        String uuidToken = map.get("authorization").toString();
        String uuid = JwtUtils.getUUIDByJwtToken(uuidToken);
        String loginToken = redisTemplate.opsForValue().get(uuid);

        String userId = JwtUtils.getMemberIdByJwtToken(loginToken);
        String mail = JwtUtils.getMemberMailByJwtToken(loginToken);

//        //从redis获取验证码，防止重复发送
        String codeFromRedis = redisTemplate.opsForValue().get(userId+"UpdatePasswordEmail");
        if (!StringUtils.isEmpty(codeFromRedis)){
            return R.ok().message("验证码发送成功");
        }

        String code = RandomUtil.getSixBitRandom();
        R r = cmsService.sendEmail(mail, code, 2);
        if(Objects.equals(r.getCode(), ResponseEnum.SUCCESS.getCode())){
            //放入redis
            redisTemplate.opsForValue().set(userId+"UpdatePasswordEmail",code,5, TimeUnit.MINUTES);
        }
        return r;
    }

}
